package com.jfinal.code.eclipse.plugin.wizards.prop;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 读取配置文件的工具类
 * @author yaolin
 *
 */
public class PropertiesUtils {

	static final String DEFAULT_CHARSET = "UTF-8";
	static Properties properties;

	public static void load(String fileName) throws IOException {
		load(fileName, DEFAULT_CHARSET);
	}

	public static void load(String fileName, String charset) throws IOException {
		InputStream inputStream = null;
		try {
			File f = new File(fileName);
			inputStream = new FileInputStream(f);
			properties = new Properties();
			properties.load(new InputStreamReader(inputStream, charset));
		} catch (IOException e) {
			throw new IOException("Error loading properties file", e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
					inputStream = null;
				} catch (IOException e) {
				}
			}
		}
	}

	public static String get(String key) {
		if (properties == null) {
			return null;
		}
		return properties.getProperty(key);
	}

	public static String get(String key, String def) {
		String value = get(key);
		return value == null ? def : value;
	}

	public static boolean getBoolean(String key) {
		String value = get(key);
		try {
			return Boolean.valueOf(value);
		} catch (Exception e) {
		}
		return false;
	}
	
	public static boolean getBoolean (String key, boolean def) {
		String value = get(key);
		try {
			return Boolean.valueOf(value);
		} catch (Exception e) {
		}
		return def;
	}
}
